package com.w.picture.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.OriginalInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import com.w.picture.config.cos.CosProperties;
import com.w.picture.exception.BusinessException;
import com.w.picture.exception.ErrorCode;
import com.w.picture.manager.CosManager;
import com.w.picture.mode.dto.file.UploadPictureResult;
import com.w.picture.mode.enums.FileUploadBizEnum;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @Title: PictureUploadTemplate
 * @Author wzp
 * @Date 2025/1/9 10:17
 * @description: 图片上传模板
 */
@Slf4j
public abstract class PictureUploadTemplate {
    @Resource
    private CosManager cosManager;
    @Resource
    protected CosProperties cosProperties;

    /**
     * 上传图片的模板方法
     *
     * @param inputSource      输入源
     * @param uploadPathPrefix 上传路径前缀
     * @param bizEnum          业务场景枚举 通过枚举来控制上传的文件路径、校验规则等待信息
     *                         <p>
     *                         当前这种先创建临时文件，上传成功后删除临时文件，适合需要对文件进行额外处理的（例如：校验），如果不需要额外处理可以使用流的方式，直接传送到 cos
     *                         cosClient.putObject()
     *                         putObject(String bucketName, String key, InputStream input,ObjectMetadata metadata)
     */
    public UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix, FileUploadBizEnum bizEnum) {
        // 1.校验图片
        validPicture(inputSource, bizEnum);
        // 2.图片上传地址
        String uuid = RandomUtil.randomString(16);
        String originFilename = getOriginFilename(inputSource);
        String uploadFilename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid,
                FileUtil.getSuffix(originFilename));
        String uploadPath = String.format("%s/%s", uploadPathPrefix, uploadFilename);
        if (uploadPath.contains("?")){
            uploadPath = uploadPath.substring(0, uploadPath.lastIndexOf("?")); // 去除类似参数.jpg?OSSAccessKeyId=LTAI5t7aiMEUzu1F2xPMCdFj&Expires=1737796392&Signature=ANx2JSJjEgJdcQdcfFxBxvacIU8%3D
        }
        File file = null;
        try {
            // 3.创建临时文件
            file = File.createTempFile(uploadPath, null);
            // 4.传输图片到临时文件
            processFile(inputSource, file);
            // 5.上传图片
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);

            // 获取图片的主色调
            String imageAve = cosManager.getImageAve(uploadPath);

            // 原图信息
            OriginalInfo originalInfo = putObjectResult.getCiUploadResult().getOriginalInfo();
            String originalInfoKey = originalInfo.getKey();
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();

            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();
            if (CollUtil.isNotEmpty(objectList)) {
                CIObject compressedCiObject = objectList.get(0);
                // 缩略图默认等于压缩图
                CIObject thumbnailCiObject = compressedCiObject;
                // 有生成缩略图，才得到缩略图
                if (objectList.size() > 1) {
                    thumbnailCiObject = objectList.get(1);
                }
                // 封装压缩图返回结果
                return buildUploadPictureResult(originalInfoKey,originFilename, compressedCiObject, thumbnailCiObject,imageAve);
            }

            // 6.封装原图返回结果
            return buildUploadPictureResult(originalInfoKey,imageInfo, originFilename, file,imageAve);
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR.getCode(), "上传失败");
        } finally {
            // 7.删除临时文件
            deleteTempFile(file);
        }
    }

    /**
     * 校验图片
     *
     * @param inputSource 输入源
     * @param bizEnum     内容枚举
     */
    public abstract void validPicture(Object inputSource, FileUploadBizEnum bizEnum);

    /**
     * 获取原始文件名
     *
     * @param inputSource 输入源
     * @return 原始文件名
     */
    protected abstract String getOriginFilename(Object inputSource);

    /**
     * 处理文件
     *
     * @param inputSource 输入源
     * @param file        临时文件
     */
    protected abstract void processFile(Object inputSource, File file) throws IOException;

    /**
     * 封装压缩后的图片返回结果
     */
    private UploadPictureResult buildUploadPictureResult(String originalUrl,String originFilename, CIObject compressedCiObject,CIObject thumbnailCiObject,String imageAve) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        int picWidth = compressedCiObject.getWidth();
        int picHeight = compressedCiObject.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(compressedCiObject.getFormat());
        uploadPictureResult.setPicSize(compressedCiObject.getSize().longValue());
        // 设置图片为压缩后的地址
        uploadPictureResult.setUrl(compressedCiObject.getKey());
        // 设置缩略图地址
        uploadPictureResult.setThumbnailUrl(thumbnailCiObject.getKey());
        uploadPictureResult.setOriginalUrl(originalUrl);
        uploadPictureResult.setHost(cosProperties.getHost()); //  对象存储域名
        uploadPictureResult.setPicColor(imageAve); // 图片主色调
        return uploadPictureResult;
    }

    /**
     * 封装原图返回结果
     *
     * @param originalUrl
     * @param imageInfo
     * @param originFilename
     * @param file
     * @return
     */
    private UploadPictureResult buildUploadPictureResult(String originalUrl,ImageInfo imageInfo, String originFilename, File file,String imageAve) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        int picWidth = imageInfo.getWidth();
        int picHeight = imageInfo.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        uploadPictureResult.setPicName(originFilename);
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setUrl(originalUrl); // 压缩后的图片
        uploadPictureResult.setOriginalUrl(originalUrl); // 原图
        uploadPictureResult.setThumbnailUrl(originalUrl); // 缩略图
        uploadPictureResult.setHost(cosProperties.getHost()); //  对象存储域名
        uploadPictureResult.setPicColor(imageAve); // 图片主色调
        return uploadPictureResult;
    }

    /**
     * 删除临时文件
     */
    public void deleteTempFile(File file) {
        if (file == null || !file.exists()) {
            return;
        }
        // 删除临时文件
        boolean deleteResult = file.delete();
        if (!deleteResult) {
            log.error("file delete error, filepath = {}", file.getAbsolutePath());
        }
    }
}
